<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAcTitgawFPlN0gkNDhsj4_RSo_opgUnRZIdAg1D3WkUKp6WfpCBT6QGYfS3lPnjdU2GHgRz6Z5UZNmQ"></script>
<script type="text/javascript">
    //google.load("jquery", '1.2.6');
    google.load("maps", "2.x");
</script>
<style type="text/css" media="screen">
    #map { float:left; width:500px; height:500px; margin-right:20px;}
    
    #list { float:left; width:160px; background:#eee; list-style:none; padding:0;margin:10px 0px 0 0; }
    #list li { padding:10px; }
    #list li:hover { background:#555; color:#fff; cursor:pointer; cursor:hand; }
    
    #message { background:#555; color:#fff; position:absolute; display:none; width:100px; padding:5px; }
    #add-point { }
    fieldset{width:160px;float:left;padding:5px;margin:0 10px 0 0;}
    div.input { padding:3px 0; }
    label { display:block; font-size:80%; }
    /* input, select { width:150px; } */
    button { float:left; }
    div.error { color:red; font-weight:bold; }
</style>
<script type="text/javascript" charset="utf-8">
$(function(){
    var map = new GMap2(document.getElementById('map'));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    var burnsvilleMN = new GLatLng(10.772052224484275,106.68136596679688);
    map.setCenter(burnsvilleMN, 15);
    var bounds = new GLatLngBounds();
    var geo = new GClientGeocoder();
    
    var reasons=[];
    reasons[G_GEO_SUCCESS] = "Success";
    reasons[G_GEO_MISSING_ADDRESS] = "Missing Address";
    reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
    reasons[G_GEO_BAD_KEY] = "Bad API Key";
    reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries";
    reasons[G_GEO_SERVER_ERROR] = "Server error";
    
    // initial load points
    $.getJSON("map-service.php?action=listpoints", function(json) {
        if (json.Locations.length > 0) {
            for (i=0; i<json.Locations.length; i++) {
                var location = json.Locations[i];
                geoEncode1(location);
                //addLocation(location);
            }
            zoomToBounds();
        }
    });
    
    // phuocndt - Load location thông qua address từ database
    function geoEncode1(location) {
        var address = location.address;
        geo.getLocations(address, function (result){
            if (result.Status.code == G_GEO_SUCCESS) {
                geocode = result.Placemark[0].Point.coordinates;
                location.lat = geocode[1];
                location.lng = geocode[0];
                addLocation1(location.lat,location.lng,location.name,location.id);
                $.post("map-service.php", { 
                    action: "savepoint", 
                    lng: location.lng,
                    lat: location.lat,
                    name: location.name 
                } );
            }
        });
    }
    function addLocation1(lat,lng,name,id) {
        var point = new GLatLng(lat, lng);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        bounds.extend(marker.getPoint());
    
        $("<li />")
        //.html(name+'<div style="float:right;"><a href="map-service.php?action=deletepoint&name='+name+'">x</a></div>')
        .html(name)
        .click(function(){
            showMessage(marker, name);
        })
        .appendTo("#list");
    
        GEvent.addListener(marker, "click", function(){
            showMessage(this, name);
        });
        zoomToBounds();
    }
    // End Load location

    $("#add-point").submit(function(){
        geoEncode();
        return false;
    });
    
    function savePoint(geocode) {
        var data = $("#add-point :input").serializeArray();
        data[data.length] = { name: "lng", value: geocode[0] };
        data[data.length] = { name: "lat", value: geocode[1] };
        $.post($("#add-point").attr('action'), data, function(json){
        $("#add-point .error").fadeOut();
            if (json.status == "fail") {
                $("#add-point .error").html(json.message).fadeIn();
            }
            if (json.status == "success") {
                $("#add-point :input[name!=action]").val("");
                var location = json.data;
                addLocation(location);
                zoomToBounds();
            }
        }, "json");
    }
    
    function geoEncode() {
        var entry_street_address = $("#add-point input[name=entry_street_address]").val();
        var entry_suburb = $("#add-point input[name=entry_suburb]").val();
        var entry_state = $("#add-point input[name=entry_state]").val();
        var entry_city = $("#add-point input[name=entry_city]").val();
        var address = entry_street_address + " " + entry_suburb + " " + entry_state + " " + entry_city;
        geo.getLocations(address, function (result){
            if (result.Status.code == G_GEO_SUCCESS) {
                geocode = result.Placemark[0].Point.coordinates;
                savePoint(geocode);
            } else {
                var reason="Code "+result.Status.code;
                if (reasons[result.Status.code]) {
                    reason = reasons[result.Status.code]
                }
                $("#add-point .error").html(reason).fadeIn();
                geocode = false;
            }
        });
    }
    
    function addLocation(location) {
        var point = new GLatLng(location.lat, location.lng);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        bounds.extend(marker.getPoint());
    
        $("<li />")
        .html(location.name)
        .click(function(){
            showMessage(marker, location.name);
        })
        .appendTo("#list");
    
        GEvent.addListener(marker, "click", function(){
            showMessage(this, location.name);
        });
    }
    
    function zoomToBounds() {
        map.setCenter(bounds.getCenter());
        map.setZoom(map.getBoundsZoomLevel(bounds)-2);
    }
    
    $("#message").appendTo( map.getPane(G_MAP_FLOAT_SHADOW_PANE) );
    
    function showMessage(marker, text){
        var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
        $("#message").hide().fadeIn()
        .css({ top:markerOffset.y, left:markerOffset.x })
        .html(text);
    }
});
</script>

<?php
global $customer_id;
if($customer_id){ 
    $addPos_query = tep_db_query("select addPos from ushop_widgets where area = 'google'");
    while ($addPos = tep_db_fetch_array($addPos_query)) {
        if($addPos['addPos'] == '1'){
    ?>
    <div style="position: relative;padding-left: 20px;">
        <form id="add-point" action="map-service.php" method="POST">
            <input type="hidden" name="action" value="savepoint_2" id="action" />
            <fieldset>
                <legend>Thêm điểm vào bản đồ</legend>
                <div class="error" style="display:none;"></div>
                <div class="input">
                    <label for="name">Tên điểm</label>
                    <input type="text" name="entry_lastname" id="entry_lastname" value="" />
                </div>
                <div class="input">
                    <label for="entry_street_address">Số nhà - Tên đường</label>
                    <input type="text" name="entry_street_address" id="entry_street_address" value="" />
                </div>
                <div class="input">
                    <label for="entry_suburb">Phường</label>
                    <input type="text" name="entry_suburb" id="entry_suburb" value="" />
                </div>
                <div class="input">
                    <label for="entry_state">Quận</label>
                    <input type="text" name="entry_state" id="entry_state" value="" />
                </div>
                <div class="input">
                    <label for="entry_city">Thành phố</label>
                    <input type="text" name="entry_city" id="entry_city" value="" />
                </div>
                
                <input type="submit" value="Thêm" />
                <!--<button type="submit">Thêm</button>-->
                <ul id="list"></ul>
            </fieldset>
        </form>    	
        <div id="map"></div>
        
        <div id="message"></div>
    </div>
    <?php }else{ ?>
    <div style="position: relative; padding-left: 20px;">
        <ul id="list"></ul>
        <div id="map"></div>
        <div id="message"></div>
    </div>
    <?php }
    }
} 
?>